package com.alipay.rebate.shop.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.rebate.shop.Application;
import com.alipay.rebate.shop.dao.mapper.UjuecCreditsAddMapper;
import com.alipay.rebate.shop.dao.mapper.UserImportMapper;
import com.alipay.rebate.shop.dao.mapper.UserMapper;
import com.alipay.rebate.shop.dao.mapper.YjUserIdMapper;
import com.alipay.rebate.shop.model.UjuecCreditsAdd;
import com.alipay.rebate.shop.model.User;
import com.alipay.rebate.shop.model.UserImport;
import com.alipay.rebate.shop.model.YjUserId;
import com.alipay.rebate.shop.pojo.UserId;
import com.alipay.rebate.shop.pojo.UserImportRequset;
import com.alipay.rebate.shop.pojo.UserImportResponse;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import javax.annotation.Resource;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.security.MessageDigest;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.io.ByteArrayOutputStream;
import java.util.zip.GZIPOutputStream;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = {Application.class})
@WebAppConfiguration
public class UserImportUtil {

	@Resource
	UserImportMapper userImportMapper;
	@Resource
	YjUserIdMapper yjUserIdMapper;
	@Resource
	UjuecCreditsAddMapper ujuecCreditsAddMapper;
	@Resource
	UserMapper userMapper;
	Logger logger = LoggerFactory.getLogger(UserImportUtil.class);

	public List<UserImport> getUserImportList(){
		List<UserImport> userImports = userImportMapper.selectAll();
		for (UserImport userImport : userImports) {
			if (userImport.getWxUnionid() == null){
				userImport.setWxUnionid("");
			}
			if (userImport.getAlipay() == null){
				userImport.setAlipay("");
			}
			if (userImport.getAlipayName() == null){
				userImport.setAlipayName("");
			}
		}
		return userImports;
	}

	public String getUserImports(List<UserImport> userImports){
//		List<UserImport> userImports = userImportMapper.selectAll();
		List<UserImportRequset> userImportRequsets = new ArrayList<>();
		for (UserImport userImport : userImports) {
			UserImportRequset requset = new UserImportRequset();
			requset.setWx_unionid("");
			if (userImport.getUserName() != null) {
				requset.setUser_name(userImport.getUserName());
			}else{
				requset.setUser_name("test");
			}
			requset.setUser_level("1");
			requset.setUphone(userImport.getPhone());
			requset.setMoney(userImport.getMoney());
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (userImport.getLoginTime() != null) {
				String login = simpleDateFormat.format(userImport.getLoginTime());
				requset.setLogin_time(login);
			}else{
				requset.setLogin_time("");
			}
			if (userImport.getCreateTime() != null) {
				String create = simpleDateFormat.format(userImport.getCreateTime());
				requset.setCreate_time(create);
			}else{
				requset.setCreate_time("");
			}
			requset.setAgent_level("");
			requset.setJifen(userImport.getJifen());
			requset.setAvatar(userImport.getAvatar());
			if (userImport.getAlipay() != null) {
				requset.setAlipay(userImport.getAlipay());
			}else{
				requset.setAlipay("");
			}
			if (userImport.getAlipayName() != null) {
				requset.setAlipay_name(userImport.getAlipayName());
			}else{
				requset.setAlipay_name("");
			}
			requset.setAgent_create_time("");
			userImportRequsets.add(requset);
			if (userImportRequsets.size() == 100){
				break;
			}
		}

		String jsonString = JSON.toJSONString(userImportRequsets);
		logger.debug("getUserImports jsonString is : {}",jsonString);
		System.out.println(jsonString);
		return jsonString;
	}

    public String doPOST(String urlAddress, String params) {
        try {
            URL url = new URL(urlAddress);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("encoding", "UTF-8");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            OutputStream outputStream = connection.getOutputStream();
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
            bufferedWriter.write(params);
            bufferedWriter.flush();
            InputStream inputStream = connection.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            StringBuilder stringBuilder = new StringBuilder();
            while ((line = bufferedReader.readLine()) != null) {
                stringBuilder.append(line);
            }
           
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            
            bufferedWriter.close();
            outputStreamWriter.close();
            outputStream.close();
            
            return stringBuilder.toString();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
	
	private String MD5(String s) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			byte[] bytes = md.digest(s.getBytes("utf-8"));
			return toHex(bytes);
		}catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	private String toHex(byte[] bytes) {
		final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
		StringBuilder ret = new StringBuilder(bytes.length * 2);
		for (int i=0; i<bytes.length; i++) {
			ret.append(HEX_DIGITS[(bytes[i] >> 4) & 0x0f]);
			ret.append(HEX_DIGITS[bytes[i] & 0x0f]);
		}
		
		return ret.toString();
	}
	
	private String compress(String str) throws IOException
	{ 
	  ByteArrayOutputStream os = new ByteArrayOutputStream(str.length()); 
	  GZIPOutputStream gos = new GZIPOutputStream(os); 
	  gos.write(str.getBytes()); 
	  os.close();
	  gos.close(); 
	  return Base64.getEncoder().encodeToString(os.toByteArray()); 
	}

	/**
	 * 同步最新的用户数据
	 */
	@Test
	public void importUser(){
		List<User> users = userMapper.selectAll();
		userImportMapper.deleteAll();
		for (User user : users) {
			UserImport userImport = new UserImport();
			userImport.setUserId(user.getUserId());
			userImport.setInvId(user.getParentUserId());
			userImport.setPhone(user.getPhone());
			userImport.setUserName(user.getUserNickName());
			userImport.setAlipay(user.getAlipayAccount());
			userImport.setAlipayName(user.getRealName());
			userImport.setJifen(user.getUserIntgeral());
			userImport.setAvatar(user.getUserHeadImage());
			userImport.setCreateTime(user.getCreateTime());
			userImport.setLoginTime(user.getLastLoginTime());
			userImport.setMoney(user.getUserAmount());
			userImport.setUit(user.getUserIntgeralTreasure());
			userImportMapper.insert(userImport);
		}
	}

	ObjectMapper objectMapper = new ObjectMapper();
	/**
	 * 导入用户信息
	 */
    @Test
	public void userImport() throws IOException {
		List<UserImport> userImports = getUserImportList();
		logger.debug("userImports is : {}",userImports);
		logger.debug("userImports.size is : {}",userImports.size());
		yjUserIdMapper.deleteAll();
		int listSize=userImports.size();
		int toIndex=100;
		int keyToken = 0;
		for (int i = 0;i<userImports.size();i+=100) {
			if(i+100>listSize){        //作用为toIndex最后没有100条数据则剩余几条newList中就装几条
				toIndex=listSize-i;
			}
			List<UserImport> newList = userImports.subList(i,i+toIndex);
			logger.debug("newList.size is : {}",newList.size());
			long timestamp = System.currentTimeMillis() / 1000;
			String compressStr = "";
			try {
				compressStr = compress(getUserImports(newList));
			} catch (Exception ex) {

			}
			Map<String, String> map = new HashMap<String, String>();
			map.put("service", "ujuec_user_import");
			map.put("appKey", "E14V0pwyTZrJZAB9");
			map.put("timestamp", timestamp + "");
			map.put("data", compressStr);
			Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
				public int compare(String str1, String str2) {
					return str1.compareTo(str2);
				}
			});
			sortMap.putAll(map);
			String link = "";
			String silink = "";
			for (Map.Entry<String, String> entry : sortMap.entrySet()) {
				try {
					link += (link == "" ? "" : "&") + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8");
					silink += (silink == "" ? "" : "&") + entry.getKey() + "=" + entry.getValue();
				} catch (Exception e) {
				}

			}

			String sign = MD5(silink + "c07627d655f824fee49b0252d3b89595");
			link += "&sign=" + sign;
//			String s1 = doPOST("http://test.ujuec.com/gw", link);
			String s1 = doPOST("https://ujuecnew.zjk.taeapp.com/gw", link);
			System.out.println(s1);

			String substring = s1.substring(s1.indexOf("["), s1.lastIndexOf("]")+1);
			logger.debug("substring is : {}",substring);
			System.out.println(substring);

			List<UserImportResponse> list = new ArrayList<>();
			list = JSONObject.parseArray(substring, UserImportResponse.class);

			for (UserImportResponse userImportResponse : list) {
				String s = yjUserIdMapper.selectYjUserId(userImportResponse.getUid());
				if (s != null){
					continue;
				}
				yjUserIdMapper.insertYjUserId(userImportResponse.getUid(),userImportResponse.getPhone());
			}
			logger.debug("parseArray is : {}",list);
			try {
				Thread.sleep(2000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			keyToken++;
		}
	}

	/**
	 * 绑定用户关系
	 */
	@Test
	public void user_relation_bind(){
		List<User> users = userMapper.selectParentUserIdNotNull();
		List<UserId> userIds = new ArrayList<>();
		for (User user : users) {
			String userPhone = userMapper.selectPhone(user.getUserId());
			String invPhone = userMapper.selectPhone(user.getParentUserId());
			String userId = yjUserIdMapper.selectUserId(userPhone);
			String invId = yjUserIdMapper.selectUserId(invPhone);
			UserId userId2 = new UserId();
			userId2.setUid(userId);
			userId2.setInvId(invId);
			userIds.add(userId2);
		}

		logger.debug("userIds is : {}",userIds);

		for (UserId id : userIds) {
			long timestamp = System.currentTimeMillis() / 1000;
			Map<String, String> map = new HashMap<String, String>();
			map.put("service", "ujuec_user_relation_bind");
			map.put("appKey", "E14V0pwyTZrJZAB9");
			map.put("uid", id.getUid());
			map.put("inv_id", id.getInvId());
//			map.put("uid", "17442491");
//			map.put("inv_id", "17441699");
			map.put("timestamp", timestamp + "");
			Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
				public int compare(String str1, String str2) {
					return str1.compareTo(str2);
				}
			});
			sortMap.putAll(map);
			String link = "";
			String silink = "";
			for (Map.Entry<String, String> entry : sortMap.entrySet()) {
				try {
					link += (link == "" ? "" : "&") + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8");
					silink += (silink == "" ? "" : "&") + entry.getKey() + "=" + entry.getValue();
				} catch (Exception e) {
				}

			}
			String sign = MD5(silink + "c07627d655f824fee49b0252d3b89595");
			link += "&sign=" + sign;
//	    	String s1 = doPOST("http://test.ujuec.com/gw", link);
			String s1 = doPOST("https://ujuecnew.zjk.taeapp.com/gw", link);
			System.out.println(s1);
			try {
				Thread.sleep(2000L);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 加集分宝
	 */
	@Test
	public void ujuecCreditsAdd() throws IOException {
		String desc = "测试";
		try{
			desc = new String(desc.getBytes("gbk"),"utf-8");
		}catch(Exception e){}
		List<UserImport> userImports = userImportMapper.selectUser();
		for (UserImport userImport : userImports) {
			UjuecCreditsAdd ujuecCreditsAdd = ujuecCreditsAddMapper.selectByPhone(userImport.getPhone());
			if (ujuecCreditsAdd != null){
				logger.debug("该用户已经添加过集分宝，不能重复添加");
				continue;
			}
			long timestamp = System.currentTimeMillis() / 1000;
			User user = userMapper.selectById(userImport.getUserId());
			logger.debug("user uit is : {}",user.getUserIntgeralTreasure());
			Map<String, String> map = new HashMap<String, String>();
			map.put("service", "ujuec_credits_add");
			map.put("appKey", "E14V0pwyTZrJZAB9");
			map.put("bizId", user.getPhone());
			map.put("desc", desc);
			map.put("uphone", user.getPhone());
//			map.put("ucode", "");
			map.put("timestamp", timestamp+"");
			map.put("credits",String.valueOf(user.getUserIntgeralTreasure()));
			map.put("type", "2");
			Map<String, String> sortMap = new TreeMap<String, String>(new Comparator<String>() {
				public int compare(String str1, String str2) {
					return str1.compareTo(str2);
				}
			});
			sortMap.putAll(map);
			String link = "";
			String silink = "";
			for (Map.Entry<String, String> entry : sortMap.entrySet()) {
				try {
					link += (link == "" ? "" : "&") + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "utf-8");
					silink += (silink == "" ? "" : "&") + entry.getKey() + "=" + entry.getValue();
				} catch (Exception e) {
				}

			}
			String sign = MD5(silink + "c07627d655f824fee49b0252d3b89595");
			link += "&sign=" + sign;
			//String s1 = doPOST("http://test.ujuec.com/gw", link);
			String s1 = doPOST("https://ujuecnew.zjk.taeapp.com/gw", link);
			System.out.println(s1);

			String substring = s1.substring(s1.indexOf(":")+2, s1.indexOf(",") - 1);
			System.out.println(substring);
			if (substring.equalsIgnoreCase("ok")) {
				ujuecCreditsAddMapper.insertUjuecCreditsAdd(userImport.getPhone());
			}
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}
}